package CampusAnalyticsSystem

import scala.annotation.tailrec
import scala.collection.mutable

object CampusAnalyticsSystem extends App {
  // 1. 数据结构定义
  case class DetailedScore(
                            studentId: String,
                            courseId: String,
                            score: Double,
                            semester: String,
                            classRank: Int
                          )

  case class CourseEvaluation(
                               courseId: String,
                               studentId: String,
                               rating: Double,
                               comment: String,
                               date: String
                             )

  case class ResourceUsage(
                            resourceId: String,
                            resourceType: String,
                            userId: String,
                            duration: Double,   // 小时
                            date: String
                          )

  case class Department(
                         id: String,
                         name: String,
                         subDepartments: List[Department],
                         facultyCount: Int
                       )

  // 2. 模拟数据
  // 成绩数据
  val scores = List(
    DetailedScore("S2025001", "C101", 85.0, "2025-1", 5),
    DetailedScore("S2025001", "C102", 90.0, "2025-1", 3),
    DetailedScore("S2025002", "C101", 92.0, "2025-1", 2),
    DetailedScore("S2025002", "C102", 82.0, "2025-1", 7),
    DetailedScore("S2025003", "C101", 76.0, "2025-1", 8),
    DetailedScore("S2025003", "C102", 86.0, "2025-1", 4),
    DetailedScore("S2025001", "C101", 88.0, "2025-2", 4),
    DetailedScore("S2025001", "C102", 92.0, "2025-2", 2),
    DetailedScore("S2025002", "C101", 90.0, "2025-2", 3)
  )

  // 课程评价数据
  val evaluations = List(
    CourseEvaluation("C101", "S2025001", 4.5, "老师讲得很好，内容丰富", "2025-06-10"),
    CourseEvaluation("C101", "S2025002", 4.0, "还行，作业有点多", "2025-06-11"),
    CourseEvaluation("C101", "S2025003", 3.5, "一般般，课堂互动少", "2025-06-10"),
    CourseEvaluation("C102", "S2025001", 5.0, "非常好，收获很大", "2025-06-12"),
    CourseEvaluation("C102", "S2025002", 3.0, "内容太难，跟不上", "2025-06-11")
  )

  // 资源使用数据
  val resourceUsages = List(
    ResourceUsage("R101", "教室", "T1001", 2.0, "2025-06-01"),
    ResourceUsage("R101", "教室", "T1002", 3.0, "2025-06-03"),
    ResourceUsage("L201", "实验室", "T1001", 4.0, "2025-06-02"),
    ResourceUsage("R101", "教室", "T1001", 2.5, "2025-06-05"),
    ResourceUsage("L201", "实验室", "T1003", 3.5, "2025-06-04")
  )

  // 组织架构数据
  val csDept = Department("D101", "计算机系", List(
    Department("D1011", "软件工程", Nil, 15),
    Department("D1012", "计算机科学", Nil, 20)
  ), 0)

  val mathDept = Department("D102", "数学系", List(
    Department("D1021", "应用数学", Nil, 10),
    Department("D1022", "基础数学", Nil, 8)
  ), 0)

  val college = Department("D001", "理工学院", List(csDept, mathDept), 0)

  // 3. 学生成绩分析模块（匿名函数+高阶函数）
  object ScoreAnalysis {
    // 按学生分组
    val byStudent = (s: DetailedScore) => s.studentId
    // 按课程分组
    val byCourse = (s: DetailedScore) => s.courseId
// 按学期分组
val bySemester = (s: DetailedScore) => s.semester

    // 高阶函数：通用成绩分析
    def analyzeScores[T](
                          data: List[DetailedScore],
                          groupFunc: DetailedScore => T,
                          aggFunc: List[DetailedScore] => Double
                        ): Map[T, Double] = {
      data.groupBy(groupFunc).map { case (key, group) =>
        (key, aggFunc(group))
      }
    }

    // 分析函数：平均分
    val averageScore = (group: List[DetailedScore]) =>
      group.map(_.score).sum / group.size

    // 分析函数：最高分
    val maxScore = (group: List[DetailedScore]) =>
      group.map(_.score).max

// 分析结果展示
def printAnalysis[T](title: String, results: Map[T, Double]): Unit = {
  println(s"=== $title ===")
  results.foreach { case (key, value) =>
    println(f"$key: $value%.1f")
  }
}
  }

  // 使用成绩分析模块

  import ScoreAnalysis._

  val courseAvg = analyzeScores(scores, byCourse, averageScore)
  printAnalysis("各课程平均分", courseAvg)

  val studentMax = analyzeScores(scores, byStudent, maxScore)
  printAnalysis("\n学生最高分", studentMax)

  // 4. 课程评价分析模块（偏函数+函数组合）
  object EvaluationAnalysis {
    // 情感分析偏函数：从评价中提取情感倾向
    val sentimentAnalyzer: PartialFunction[String, Double] = {
      case comment if comment.contains("好") || comment.contains("优秀") || comment.contains("收获大") => 0.8
      case comment if comment.contains("一般") || comment.contains("还行") => 0.5
      case comment if comment.contains("差") || comment.contains("跟不上") || comment.contains("少") => 0.2
    }

    // 评价处理流水线：提取情感 -> 结合评分 -> 综合得分
    val processEvaluation = (eval: CourseEvaluation) => {
      val sentiment = if (sentimentAnalyzer.isDefinedAt(eval.comment)) {
        sentimentAnalyzer(eval.comment)
      } else 0.5 // 无法分析的评论默认中性

      // 综合得分：评分(0-5)标准化为0-1，与情感各占50%
      (eval.rating / 5.0 * 0.5) + (sentiment * 0.5)
    }

    // 按课程分析综合评价
    def analyzeCourseEvaluations(data: List[CourseEvaluation]): Map[String, Double] = {
      data.groupBy(_.courseId).map { case (courseId, evals) =>
        val avgScore = evals.map(processEvaluation).sum / evals.size
        (courseId, avgScore)
      }
    }
  }

  // 使用评价分析模块

  import EvaluationAnalysis._

  val courseScores = analyzeCourseEvaluations(evaluations)
  println("\n=== 课程综合评价得分（0-1） ===")
  courseScores.foreach { case (courseId, score) =>
    println(f"$courseId: $score%.2f")
  }

  // 5. 资源使用分析模块（闭包+高阶函数）
  object ResourceAnalysis {
    // 创建资源使用追踪器（闭包）
    def createResourceTracker(): ResourceUsage => Map[String, (Int, Double)] = {
      val usageStats = mutable.Map[String, (Int, Double)]().withDefaultValue((0, 0.0))

      (usage: ResourceUsage) => {
        val (count, totalDuration) = usageStats(usage.resourceId)
        val newCount = count + 1
        val newDuration = totalDuration + usage.duration
        usageStats(usage.resourceId) = (newCount, newDuration)
        usageStats.toMap
      }
    }

    // 分析资源使用趋势
    def analyzeUsageTrends(data: List[ResourceUsage]): Map[String, (Int, Double)] = {
      val tracker = createResourceTracker()
      data.foreach(tracker) // 处理所有使用记录
      tracker(ResourceUsage("", "", "", 0, "")) // 获取最终统计
    }
  }

  // 使用资源分析模块

  import ResourceAnalysis._

  val resourceStats = analyzeUsageTrends(resourceUsages)
  println("\n=== 资源使用统计（次数/总时长） ===")
  resourceStats.foreach { case (resourceId, (count, duration)) =>
    println(f"$resourceId: $count 次, $duration%.1f 小时")
  }

// 6. 组织架构分析模块（尾递归+高阶函数）
object OrganizationAnalysis {
  // 尾递归计算总人数
  def calculateTotalFaculty(dept: Department): Int = {
    @tailrec
    def countHelper(remaining: List[Department], total: Int): Int = {
      remaining match {
        case Nil => total
        case head :: tail =>
          countHelper(head.subDepartments ++ tail, total + head.facultyCount)
      }
    }

    countHelper(List(dept), 0)
  }

  // 按层级获取部门列表
  def getDepartmentHierarchy(dept: Department): List[String] = {
    @tailrec
    def hierarchyHelper(remaining: List[(Department, Int)], result: List[String]): List[String] = {
      remaining match {
        case Nil => result.reverse
        case (dept, level) :: tail =>
          val indent = "  " * level
          val newResult = s"$indent${dept.name} (${calculateTotalFaculty(dept)}人)" :: result
          val subDepts = dept.subDepartments.map(d => (d, level + 1))
          hierarchyHelper(subDepts ++ tail, newResult)
      }
    }

    hierarchyHelper(List((dept, 0)), Nil)
  }
}

  // 使用组织架构分析模块

  import OrganizationAnalysis._

  println("\n=== 组织架构与教职工人数 ===")
  val hierarchy = getDepartmentHierarchy(college)
  hierarchy.foreach(println)
}